package com.wqh.zeromq.inform;

import com.baosight.hdjni.HDErrcode;
import com.baosight.hdsdk.HDDataProvider;
import com.baosight.hdsdk.HDTagManager;
import com.baosight.hdsdk.common.HDTagDataType;
import com.baosight.hdsdk.domain.data.HDBasicTag;
import com.baosight.hdsdk.domain.data.HDDataConnection;
import com.baosight.hdsdk.domain.data.HDRecord;
import com.baosight.hdsdk.exception.HDSdkException;
import com.wqh.zeromq.util.HDManager;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.json.JSONObject;
import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;


/**连接远程数据库，并获取最新tag数据
 * @author 吴起航
 */
public class SubscriberRemote {

    private static Logger logger = Logger.getLogger(SubscriberRemote.class.getSimpleName());

    private static HDDataConnection connection;
    private static HDTagManager manager;
    private static HDDataProvider provider;

    public static void main(String[] args) {

        connection = HDManager.getConnection();
        manager = connection.getTagManager();
        provider = new HDDataProvider(connection);

        HDErrcode errcode = new HDErrcode();
        List<ImmutablePair<HDRecord, Integer>> list=null;
        List<HDBasicTag>  initList;
        List<Integer>  tagIdList = new ArrayList<>();
        Map<Integer, String> id_NameMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        //获取所有服务器上的普通tag点数据
        try {
            initList = manager.queryBasicTagsSimple("*","*",HDTagDataType.FLOAT32,true);

            logger.info("已获取所有普通tag"+initList.size());
            for(HDBasicTag tag:initList){
                String tagName = tag.getName();
                int tagId = tag.getId();

                id_NameMap.put(tagId,tagName);
                //用于查询value
                tagIdList.add(tagId);
            }
            //开始查询每个tag对应的value
            list = provider.querySnapshotsByIDs(tagIdList,errcode);

            for(ImmutablePair pair:list){
                HDRecord record= (HDRecord)pair.getKey();
                int tagId=record.getBelongTagID();
                String tagValue=record.getValueStr();
                String tagName=id_NameMap.get(tagId);
                map.put(tagName,tagValue);
            }

        } catch (HDSdkException e) {
            logger.warning("未查询到任何有用tag点或未查询到tag对应的value");
            e.printStackTrace();
        }

        logger.info("已获得服务器的tag初始数据"+map.size());

        //开始进行通信
        try (ZContext context = new ZContext()){
            //创建“发布/订阅”模式中的“订阅”的socket
            ZMQ.Socket subscriber = context.createSocket(SocketType.SUB);

            // 设置一个Socket标示,当subscriber重新连接之后可以从上次中断的地方读取到终断之后错过的数据
            //subscriber.setConnectRid(String.valueOf(new Random().nextInt(100))); // 在Java中暂时还不支持
            //subscriber.connect("tcp://10.25.167.49:5502");
            subscriber.connect("tcp://*:5555");
            //设置订阅主题,只接受信息头为Weather的消息
            String topicName = "";

            subscriber.subscribe(topicName.getBytes());
            while(!Thread.currentThread().isInterrupted()&& map.size() <= 100){
                String message = subscriber.recvStr(0);
                logger.info(message);

                String messageName = message.substring(0,message.indexOf("[")-1);
                String messageValue = message.substring(message.indexOf("[")+1,message.length()-1);
                JSONObject jsonObject = new JSONObject(messageValue);


                for(String key : jsonObject.keySet()){
                    map.put(key,jsonObject.get(key));
                }
            }
            logger.info(map.toString());
        }
    }
}
